package com.musifind.activities;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.widget.VideoView;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.musifind.chat.Config;
import com.musifind.utils.ConnectionDetector;
import com.musifind.utils.SessionManager;

public class SplashActivity extends Activity implements SurfaceHolder.Callback {
	GoogleCloudMessaging gcm;
	private static final String TAG = "GCMUtils";
	private String regId;
	private SessionManager session;

	MediaPlayer mediaPlayer;
	SurfaceView surfaceView;
	SurfaceHolder surfaceHolder;
	boolean pausing = false;
	private VideoView videoIntro;
	// to manage where branches the splash activity
	private boolean isGuest;
	private boolean isFacebookUser;
	SharedPreferences sharedPrefs;

	// flag for Internet connection status
	Boolean isInternetPresent = false;

	// Connection detector class
	ConnectionDetector cd;

	String now_playing, earned;

	private static int SPLASH_TIME_OUT = 3000;

	// AnimationDrawable rocketAnimation;
	//
	// public boolean onTouchEvent(MotionEvent event) {
	// if (event.getAction() == MotionEvent.ACTION_DOWN) {
	// rocketAnimation.start();
	// return true;
	// }
	// return super.onTouchEvent(event);
	// }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// remove title bar
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// remove the action bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_splash);

		getWindow().setFormat(PixelFormat.UNKNOWN);

		videoIntro = (VideoView) findViewById(R.id.videoIntro);
		String uriPath = "android.resource://com.musifind.activities/" + R.raw.musifind_intro;
		Uri uri = Uri.parse(uriPath);
		videoIntro.setVideoURI(uri);
		videoIntro.requestFocus();
		videoIntro.start();

		sharedPrefs = getSharedPreferences("register_info", MODE_PRIVATE);

		session = new SessionManager(getApplicationContext());
		gcm = GoogleCloudMessaging.getInstance(this);
		// Thread thReg = new Thread() {
		// @Override
		// public void run() {
		// try {
		// GCMUtils gcmUtils = new GCMUtils();
		// gcmUtils.registerGCM();
		// synchronized (this) {
		// wait(1000);
		// }
		// } catch (Exception e) {
		// Log.e("Splash Activity", "Something has gone wrong");
		//
		// } finally {
		// Intent i = new Intent(SplashActivity.this, WelcomeActivity.class);
		// startActivity(i);
		// }
		// }
		// };
		// thReg.start();

		// ImageView rocketImage = (ImageView) findViewById(R.id.imgLogo);
		// rocketImage.setBackgroundResource(R.drawable.animation_splash);
		// rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
		// rocketImage.post(new Runnable() {
		// public void run() {
		// rocketAnimation.start();
		// }
		// });

		isGuest = session.isGuest();
		isFacebookUser = session.isFaceUser();

		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// creating connection detector class instance
				cd = new ConnectionDetector(getApplicationContext());

				// get Internet status
				isInternetPresent = cd.isConnectingToInternet();
				// isInternetPresent = false;
				if (isInternetPresent) {
					registerGCM();
					// SharedPreferences sharedPreferences = getSharedPreferences("register_info", MODE_PRIVATE);
					// String registrationId = sharedPreferences.getString(REG_ID, "");
					// if (registrationId.isEmpty()) {
					// GCMUtils gcmUtils = new GCMUtils(gcm);
					// String regId = gcmUtils.registerGCM();
					// SharedPreferences.Editor editor = sharedPreferences.edit();
					// editor.putString(REG_ID, regId);
					// editor.commit();
					// }
					synchronized (this) {
						try {
							Thread.sleep(4000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					if (isGuest || isFacebookUser) {
						Intent i = new Intent(SplashActivity.this, WelcomeActivity.class);
						startActivity(i);
					} else {
						Intent i = new Intent(SplashActivity.this, HomepageActivity.class);
						startActivity(i);
					}

					// Intent i = new Intent(SplashActivity.this, MainActivity.class);
					// i.putExtra("now_playing", now_playing);
					// i.putExtra("earned", earned);
					// startActivity(i);
					// close this activity
					finish();
				} else {
					showAlertDialog(SplashActivity.this, "Bağlantı yok!",
							"Uygulamayı kullanabilmek için internet bağlantınız olmalı.", false);
				}

			}
		}, SPLASH_TIME_OUT);

	}

	/*
	 * Async Task to make http call
	 */
	private class PrefetchData extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// before making http calls
			Log.e("INTERNET", "Pre execute");

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// creating connection detector class instance
			cd = new ConnectionDetector(getApplicationContext());
			// get Internet status
			isInternetPresent = cd.isConnectingToInternet();

			// check for Internet status
			if (isInternetPresent) {
				isInternetPresent = true;
			} else {
				isInternetPresent = false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// After completing http call
			// will close this activity and lauch main activity

			if (isInternetPresent) {
				Intent i = new Intent(SplashActivity.this, WelcomeActivity.class);
				i.putExtra("now_playing", now_playing);
				i.putExtra("earned", earned);
				startActivity(i);

				// close this activity
				finish();
			} else {
				showAlertDialog(SplashActivity.this, "No Internet Connection", "You don't have internet connection.",
						false);
			}
		}
	}

	@SuppressWarnings("deprecation")
	public void showAlertDialog(Context context, String title, String message, Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();
		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		});
		// Showing Alert Message
		alertDialog.show();
	}

	// GCM
	public String registerGCM() {
		gcm = GoogleCloudMessaging.getInstance(this);
		regId = session.getGCMRegistrationId();
		if (TextUtils.isEmpty(regId)) {
			registerInBackground();
			Log.d(TAG, "registerGCM - successfully registered with GCM server - regId: " + regId);
		} else {
			Log.d(TAG, "Regid already available: " + regId);
		}
		return regId;
	}

	private void registerInBackground() {
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String msg = "";
				try {
					if (gcm == null) {
						gcm = GoogleCloudMessaging.getInstance(session.getContext());
					}
					regId = gcm.register(Config.GOOGLE_PROJECT_ID);
					Log.d("RegisterActivity", "registerInBackground - regId: " + regId);
					msg = "Device registered, registration ID=" + regId;
					session.createGCMRegIdSession(regId);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
					Log.d(TAG, "Error: " + msg);
				}
				Log.d(TAG, "AsyncTask completed: " + msg);
				return msg;
			}

			@Override
			protected void onPostExecute(String msg) {
				Log.d(TAG, "Registered with GCM Server." + msg);
			}
		}.execute(null, null, null);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
	}

}
